import 'dart:convert';
import 'package:book_manager_app/app/utils/common/app_manager.dart';

class AccountManager {

  // 
  static const String _key = "login_history";

 /// 获取历史账号和密码列表
  static List<Map<String, String>> getLoginHistory() {
    // 读取数据后进行类型转换
    List<dynamic>? jsonStringList = localStorageRead(_key);
    if (jsonStringList == null) return [];

    return jsonStringList.map((jsonString) {
      return Map<String, String>.from(json.decode(jsonString));
    }).toList();
  }

  /// 添加新的账号和密码到历史记录
  static Future<void> addAccountToHistory(String account, String password) async {
    List<dynamic>? jsonStringList = localStorageRead(_key);
    List<String> historyList = jsonStringList?.cast<String>() ?? [];
    
    Map<String, String> newEntry = {account: password};

    // 删除已存在的相同账号（若存在）
    historyList.removeWhere((jsonString) {
      Map<String, String> entry = Map<String, String>.from(json.decode(jsonString));
      return entry.containsKey(account);
    });

    historyList.insert(0, json.encode(newEntry));
    // 限制列表长度为10
    if (historyList.length > 10) {
      historyList = historyList.sublist(0, 10);
    }
    await localStorageWrite(_key, historyList);
  }

  /// 获取某个账号的密码
  static Future<String?> getPasswordForAccount(String account) async {
    List<Map<String, String>> history = getLoginHistory();
    for (var entry in history) {
      if (entry.containsKey(account)) {
        return entry[account];
      }
    }
    return null;
  }
}